package com.hqd.jjvm.classformat.attributeinfo;

import com.hqd.jjvm.classformat.ClassFile;
import com.hqd.jjvm.util.HexStrTransformUtil;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

@Getter
@NoArgsConstructor
public class BootstrapMethodsAttribute extends AttributeInfo {
	private Integer bootstrapMethodLength;
	private List<BootstrapMethod> bootstrapMethodList;

	public BootstrapMethodsAttribute(Integer attributeNameIndex, Integer attributeLength, Integer bootstrapMethodLength, List<BootstrapMethod> bootstrapMethodList) {
		super(attributeNameIndex, attributeLength);
		this.bootstrapMethodLength = bootstrapMethodLength;
		this.bootstrapMethodList = bootstrapMethodList;
	}

	class BootstrapMethod {
		private Integer bootstrapMethodRef;
		private Integer bootstrapArgumentLength;
		private List<Integer> argumentIndexList;

		public BootstrapMethod(Integer bootstrapMethodRef, Integer bootstrapArgumentLength, List<Integer> argumentIndexList) {
			this.bootstrapMethodRef = bootstrapMethodRef;
			this.bootstrapArgumentLength = bootstrapArgumentLength;
			this.argumentIndexList = argumentIndexList;
		}
	}

	@Override
	protected BootstrapMethodsAttribute newAttributeInfo(Integer attributeNameIndex, Integer attributeLength, ClassFile classFile) {
		this.bootstrapMethodLength = HexStrTransformUtil.parseHexToInt(classFile.readU2());
		List<BootstrapMethod> bootstrapMethods = new ArrayList<>(bootstrapMethodLength);
		for (int i = 0; i < bootstrapMethodLength; i++) {
			Integer refIndex = HexStrTransformUtil.parseHexToInt(classFile.readU2());
			Integer argumentLength = HexStrTransformUtil.parseHexToInt(classFile.readU2());
			List<Integer> argumentList = new ArrayList<>(argumentLength);
			for (int j = 0; j < argumentLength; j++) {
				argumentList.add(HexStrTransformUtil.parseHexToInt(classFile.readU2()));
			}
			bootstrapMethods.add(new BootstrapMethod(refIndex, argumentLength, argumentList));
		}
		this.bootstrapMethodList = bootstrapMethods;
		return this;
	}
}
